package com.tdzx.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts.Photo;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tdzx.R;
import com.tdzx.adapter.TestExpandablelistAdapter;
import com.tdzx.constant.Constant;
import com.tdzx.entity.Contact;
import com.tdzx.util.Animations;
import com.tdzx.view.CustomExpandableListView;
import com.tdzx.view.CustomLetterView;
import com.tdzx.view.CustomLetterView.OnTouchingLetterChangedListener;

/**
 * 修改车型
 * 
 * @author utopia
 * 
 */
public class XgcxActivity extends BaseActivity_NoBar implements
		OnChildClickListener, OnGroupCollapseListener,
		OnTouchingLetterChangedListener {
	// 城市
	private final String[] ZIMU = {"B", "C","F", "G", "H","J","K","L",
			"N",  "S","T",  "W", "X","Y", "Z" };
	

	private CustomExpandableListView expandable;
	private CustomLetterView letter_view;

	private List<String> groupList = new ArrayList<String>();
	private ArrayList<List<Contact>> childList = new ArrayList<List<Contact>>();
	private ArrayList<ArrayList<Integer>> childList_IMG = new ArrayList<ArrayList<Integer>>();
	private TestExpandablelistAdapter testExpandablelistAdapter;

	public static ImageView iv_yy_xxpp=null;
	private Animations a = null;
	 int i = 0;
	 
	 private String pp="";
	 private String xh="";
	 
	 boolean back = false;
	 
//	 public static Map<String, String> cityMap = new HashMap<String, String>();
	 
	 AsyncHttpClient client;
	 
	 ImageView caterory_back;
	 ImageView cat_src;
	 
	 List<Contact> listContact = new ArrayList<Contact>();
	 
	 /**联系人显示名称**/
	    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
	    
	    /**电话号码**/
	    private static final int PHONES_NUMBER_INDEX = 1;
	    
	    /**头像ID**/
	    private static final int PHONES_PHOTO_ID_INDEX = 2;
	   
	    /**联系人的ID**/
	    private static final int PHONES_CONTACT_ID_INDEX = 3;
	    
	    /**获取库Phon表字段**/
	    private static final String[] PHONES_PROJECTION = new String[] {
	            Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID,Phone.CONTACT_ID };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		client = new AsyncHttpClient();
		
		
		Intent intent = getIntent();
		back = intent.getBooleanExtra("back", back);
		showProgress("正在加载数据...");
		getPhoneContacts();
		String phone = "";
		if(listContact.size() > 1) {
			for(int i = 0; i < listContact.size(); i++) {
				phone = phone + listContact.get(i).getContact_number() + ",";
			} 
		} else if(listContact.size() == 1) {
			phone = listContact.get(i).getContact_number();
		}
		RequestParams params = new RequestParams();
		params.put("telephones", phone);
		client.post(Constant.checkPhone,params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				finishProgress();
				if(listContact.size() > 0) {
					setContentView(R.layout.xxpp);
					Contact.getContactList(content, listContact);
					initViewTop();
					initCity();
					initView();
					setListener();
				}
				super.onSuccess(content);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				finishProgress();
				showProgress("网络错误,获取数据失败");
				super.onFailure(error, content);
			}
			
		});
//		initChildXH();
		//TODO
//		initGroupList();
//		initChildList();

	}
	
	/**得到手机通讯录联系人信息**/
    private void getPhoneContacts() {
        ContentResolver resolver = getContentResolver();

        // 获取手机联系人
        Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,PHONES_PROJECTION, null, null, null);


        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {

                //得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                //当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                
                Contact contact = new Contact();
                contact.setContact_number(phoneNumber);
                //得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                contact.setContact_name(contactName);
                //得到联系人ID
                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
                contact.setContact_id(contactid);
                //得到联系人头像ID
                Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
                contact.setPhotoid(photoid);
                //得到联系人头像Bitamp
//                Bitmap contactPhoto = null;

                //photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
//                if(photoid > 0 ) {
//                    Uri uri =ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactid);
//                    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
//                    contactPhoto = BitmapFactory.decodeStream(input);
//                }
                listContact.add(contact);
            }

            phoneCursor.close();
        }
        
        Set<Contact> set = new HashSet<Contact>(listContact);
        listContact.clear();
        listContact.addAll(set);
//        for(int i = 0; i < listContact.size(); i++) {
//        	System.err.println(listContact.get(i).getContact_name() + listContact.get(i).getContact_number());
//        }
    }
	
	private void initViewTop() {
		caterory_back = (ImageView) findViewById(R.id.caterory_back);
		caterory_back.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				Log.i("ccc", "onTouch ca");
				cat_src.onTouchEvent(arg1);
				return false;
			}
		});
		
		caterory_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		cat_src = (ImageView) findViewById(R.id.cat_src);
		cat_src.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Log.i("ccc", "onTouch crc");
				return true;
			}
		});
	}
	
	private void initCity() {
//		cityMap.put("海口", "101310101");
		
		for(int i = 0; i < listContact.size(); i++) {
			if(listContact.get(i).getMemberName() != null) {
				groupList.add(String2Alpha(listContact.get(i).getMemberName()));
			} else {
				groupList.add(String2Alpha(listContact.get(i).getContact_name()));
			}
//			cityMap.put(listDX.get(i).getName(), listDX.get(i).getCode());
		}
		Set h = new HashSet(groupList);
		System.err.println(groupList);
		groupList.clear();
		groupList.addAll(h);
		System.err.println(groupList);
		String[] chars = new String[groupList.size()];
		for(int i = 0; i < groupList.size(); i++) {
			chars[i] = groupList.get(i);
		}
		Collections.sort(groupList);
		System.err.println(groupList);
		
		for(int i = 0; i < groupList.size(); i++) {
			List<Contact> l = new ArrayList<Contact>();
			for(int j = 0; j < listContact.size(); j++) {
				if(listContact.get(j).getMemberName() != null) {
					String mn = String2Alpha(listContact.get(j).getMemberName());
					if(groupList.get(i).equals(mn)) {
						l.add(0,listContact.get(j));
					}
				} else {
					String cn = String2Alpha(listContact.get(j).getContact_name());
					if(groupList.get(i).equals(cn)) {
						l.add(listContact.get(j));
					}
				}
				
			}
//			if(l.size() > 0) {
				childList.add(l);
//			}
		}
	}
	
	private void initView() {
		a = new Animations(this);
//		rl_childxh = (RelativeLayout) findViewById(R.id.rl_childxh);
//		tv_childpp = (TextView) findViewById(R.id.tv_childpp);
//		lv_childxh = (ListView) findViewById(R.id.lv_childxh);
		iv_yy_xxpp=(ImageView) findViewById(R.id.iv_yy_xxpp);
		
		expandable = (CustomExpandableListView) findViewById(R.id.expandable);
		expandable.setHeaderView(getLayoutInflater().inflate(
				R.layout.expandablelist_group_item, expandable, false));
		letter_view = (CustomLetterView) findViewById(R.id.letter_view);

		

//		i = rl_childxh.getVisibility();

		// 设置adapter并且全部展开
		testExpandablelistAdapter = new TestExpandablelistAdapter(this,
				expandable, groupList, childList, childList_IMG);
		expandable.setAdapter(testExpandablelistAdapter);
		int groupSize = groupList.size();
		for (int i = 0; i < groupSize; i++) {
			expandable.expandGroup(i);
		}

		// 获取密度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		letter_view.setList(groupList, dm);
		letter_view.invalidate();
	}

	/**
	 * 设置监听
	 */
	private void setListener() {
		letter_view.setOnTouchingLetterChangedListener(this);
		expandable.setOnChildClickListener(this);
		expandable.setOnGroupCollapseListener(this);
		expandable.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				return false;
			}
		});
		
		/*lv_childxh.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				xh=childxh.get(arg2);
				Intent intent=new Intent();
				intent.putExtra("pp", pp);
				intent.putExtra("xh", xh);
				setResult(0, intent);
				finish();
//				rl_childxh.setVisibility(View.GONE);
//				iv_yy_xxpp.setVisibility(View.GONE);
//				showToast("您选择了："+pp+"-"+xh);
			}
		});*/
		
		
		
//		expandable.setOnScrollListener(mScrollListener);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	/**
	 * 右边字母表的排列事件
	 */
	@Override
	public void onTouchingLetterChanged(int groupPosition) {
		expandable.setSelectedGroup(groupPosition);
		
		
//		letter_view.invalidate();
	}

	/**
	 * 点击child事件
	 */
	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		System.out.println("groupPosition=" + groupPosition + "    "
				+ "childPosition=" + childPosition);
		TextView tv = (TextView) v.findViewById(R.id.tv_pp);
		String text = tv.getText().toString();
//		Toast.makeText(XgcxActivity.this, text, 3000).show();
		
		
		/*Intent intent=new Intent();
		if(back) {
			intent.putExtra("city", text);
			setResult(200, intent);
		} else {
			intent.setClass(XgcxActivity.this, MyActivity.class);
			startActivity(intent);
		}
		finish();*/
		
		return false;
	}
	
	
	/**
	 *  
	 */
	@Override
	public void onGroupCollapse(int groupPosition) {
		if (expandable.isGroupExpanded(groupPosition)) {
			return;
		} else {
			expandable.expandGroup(groupPosition);
		}
	}

	private void initGroupList() {
		for (int i = 0; i < ZIMU.length; i++) {
			groupList.add(ZIMU[i]);
		}
	}

	public void exit(View view) {
		finish();
	}

	private char[] chartable =
        {
            '啊', '芭', '擦', '搭', '蛾', '发', '噶', '哈', '哈',
            '击', '喀', '垃', '妈', '拿', '哦', '啪', '期', '然',
            '撒', '塌', '塌', '塌', '挖', '昔', '压', '匝', '座'
        };

private char[] alphatable =
        {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
            'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 
            'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        };


private int[] table = new int[27];
//初始化
{
    for (int i = 0; i < 27; ++i) {
        table[i] = gbValue(chartable[i]);
    }
}

//主函数,输入字符,得到他的声母,
//英文字母返回对应的大写字母
//其他非简体汉字返回 '0'

public char Char2Alpha(char ch) {

    if (ch >= 'a' && ch <= 'z')
        return (char) (ch - 'a' + 'A');
    if (ch >= 'A' && ch <= 'Z')
        return ch;
    int gb = gbValue(ch);
    if (gb < table[0])
        return '0';
    int i;
    for (i = 0; i < 26; ++i) {
        if (match(i, gb)) break;
    }
    if (i >= 26)
        return '0';
    else
        return alphatable[i];
}

//根据一个包含汉字的字符串返回一个汉字拼音首字母的字符串
public String String2Alpha(String SourceStr){
    
    String Result = "";
    int StrLength = SourceStr.length();
    int i;
    try {
        for (i = 0; i < StrLength; i++) {
            Result += Char2Alpha(SourceStr.charAt(i));
        }
    } catch (Exception e) {
        Result = "";
    }
    if(Result.length() >= 1) {
    	Result = Result.substring(0, 1);
    }
    return Result;
}

private boolean match(int i, int gb) {
    
    if (gb < table[i])
        return false;
    int j = i + 1;

    //字母Z使用了两个标签
    while (j < 26 && (table[j] == table[i])) ++j;
    if (j == 26)
        return gb <= table[j];
    else
        return gb < table[j];
}

//取出汉字的编码
private int gbValue(char ch) {
    
    String str = new String();
    str += ch;
    try {
        byte[] bytes = str.getBytes("GB2312");
        if (bytes.length < 2)
            return 0;
        return (bytes[0] << 8 & 0xff00) + (bytes[1] &
                0xff);
    } catch (Exception e) {
        return 0;
    }
}	
}
